﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTextCodec>
#include <QStringList>

#pragma execution_character_set("utf-8")

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new  Ui::MainWindow)
{

    ui->setupUi(this);

    number_count = 0;
    strnumber.clear();

    ui->pushButton_open->setVisible(false);
    ui->pushButton_close->setVisible(false);
    ui->statusBar->showMessage("状态栏");
    ui->pushButton_templatestart->setEnabled(false);

    //桌面按钮关联
    connect(ui->pushButton_open,SIGNAL(clicked(bool)),this,SLOT(OpenClicked()));
    connect(ui->pushButton_close,SIGNAL(clicked(bool)),this,SLOT(CloseClicked()));
    connect(ui->pushButton_getimage,SIGNAL(clicked(bool)),this,SLOT(GetImageClicked()));
    connect(ui->pushButton_saveimg,SIGNAL(clicked(bool)),this,SLOT(SaveImageClicked()));
    connect(ui->pushButton_loadtemplate,SIGNAL(clicked(bool)),this,SLOT(LoadTemplateClicked()));
    connect(ui->pushButton_templatestart,SIGNAL(clicked(bool)),this,SLOT(StartTemplateClicked()));

    mythread = new MyThread;

    connect(mythread,SIGNAL(thShowImage(Mat& )),
            this,SLOT(sl_ShowImage(Mat& )),
            Qt::DirectConnection);//*,Qt::DirectConnection*/  QueuedConnection  BlockingQueuedConnection
    connect(mythread,SIGNAL(thSetNumber(int)),
            this,SLOT(sl_ShowNumber(int)),
            Qt::DirectConnection);

    OpenClicked();
    qDebug()<<QString("main thread id:")<< QThread::currentThreadId();

}

MainWindow::~MainWindow()
{
    CloseClicked();
    delete ui;
}



void MainWindow::OpenClicked()
{
    mythread->start();
}

void MainWindow::CloseClicked()
{


    mythread->closeThread();
    mythread->wait();

    ui->label->clear();
    ui->statusBar->showMessage("停止线程");

}

void MainWindow::GetImageClicked()
{
    CutImage = MatToQImage(Frame);
    cv::Mat resizeimg;
    cv::resize(Frame,resizeimg,Size(167,167));
    QImage showimg = MatToQImage(resizeimg);
    ui->label_cutimg->setPixmap(QPixmap::fromImage(showimg));
}

void MainWindow::SaveImageClicked()
{
    if(CutImage.isNull())
    {
        QMessageBox::warning(0,"警告","截图为空！",QMessageBox::Ok);
        return;
    }

    QFileDialog fileDialog;
    QString str = fileDialog.getSaveFileName(this,"open file","unknow.png","Images (*.png)");
    if(!str.isEmpty())
    {
        CutImage.save(str);
        ui->statusBar->showMessage("已保存：" + str);
    }

}

void MainWindow::StartTemplateClicked()
{
    bool setTemplateEnabl = true;
    if(ui->pushButton_templatestart->text() == "stop")
    {
        setTemplateEnabl = false;
        ui->pushButton_templatestart->setText("start");
        ui->statusBar->showMessage("停止目标识别");
    }
    else{
        setTemplateEnabl = true;
        ui->pushButton_templatestart->setText("stop");
        ui->statusBar->showMessage("开始目标识别");
    }

    mythread->SetTemplate(setTemplateEnabl,TemplateImage,ui->comboBox1->currentIndex());

}

void MainWindow::LoadTemplateClicked()
{

    QFileDialog filedialog;
    QString str = filedialog.getOpenFileName(this,"Load Template","./","Images (*.png)");
    qDebug()<<QString::number(filedialog.result())<<endl;

    if(!str.isEmpty() )
    {
        TemplateImage = imread(str.toStdString());      //,IMREAD_GRAYSCALE


        Mat resizetmp ;
        cv::resize(TemplateImage,resizetmp,Size(167,167));

        ui->label_templateimg->setPixmap(QPixmap::fromImage(MatToQImage(resizetmp)));
        ui->statusBar->showMessage("模板已加载：" + str);

        QString trs = QString::number(TemplateImage.rows) + " " +  QString::number(TemplateImage.cols);
        ui->statusBar->showMessage("图片参数："+ trs);

        ui->pushButton_templatestart->setEnabled(true);


    }


}

void MainWindow::sl_ShowImage(cv::Mat& src)
{
    Frame = src;
    ShowImage =MatToQImage(src);
    ui->label->setPixmap(QPixmap::fromImage(ShowImage));
    //qDebug()<<QString("slot thread id:")<< QThread::currentThreadId();
}

void MainWindow::sl_ShowNumber(int number)
{
    number_count++;
    strnumber+= QString::number(number);
    if(number_count >=3)
    {
        ui->statusBar->showMessage(strnumber);
        strnumber.clear();
        number_count = 0;
    }
}


QImage MainWindow::MatToQImage(const cv::Mat& mat)
{
    switch (mat.type())
    {
    // 8-bit, 4 channel
    case CV_8UC4:
    {
        QImage image(mat.data,
                     mat.cols, mat.rows,
                     static_cast<int>(mat.step),
                     QImage::Format_ARGB32);

        return image;
    }

        // 8-bit, 3 channel
    case CV_8UC3:
    {
        QImage image(mat.data,
                     mat.cols, mat.rows,
                     static_cast<int>(mat.step),
                     QImage::Format_RGB888);

        return image.rgbSwapped();
    }

        // 8-bit, 1 channel
    case CV_8UC1:
    {
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
        QImage image(mat.data,
                     mat.cols, mat.rows,
                     static_cast<int>(mat.step),
                     QImage::Format_Grayscale8);
#else
        static QVector<QRgb>  sColorTable;

        // only create our color table the first time
        if (sColorTable.isEmpty())
        {
            sColorTable.resize( 256 );

            for ( int i = 0; i < 256; ++i )
            {
                sColorTable[i] = qRgb( i, i, i );
            }
        }

        QImage image(mat.data,
                     mat.cols, mat.rows,
                     static_cast<int>(mat.step),
                     QImage::Format_Indexed8 );

        image.setColorTable(sColorTable);
#endif

        return image;
    }

        // wrong
    default:
        qDebug() << "ERROR: Mat could not be converted to QImage.";
        break;
    }
    return QImage();
}

